package com.txh.utils;

import com.alibaba.fastjson.JSONObject;
import netscape.javascript.JSObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/18.
 */
public class RestTemplateUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public static String get(ServletRequest request,String url,Map<String,?> params){
        ResponseEntity<String> responseEntity = request(request,url,HttpMethod.GET,params);
        return responseEntity.getBody();
    }

    public static String post(ServletRequest request,String url,Map<String,?> params){
        ResponseEntity<String> responseEntity = request(request,url,HttpMethod.POST,params);
        return responseEntity.getBody();
    }


    private static ResponseEntity<String> request(ServletRequest request, String url, HttpMethod method,Map<String, ?> parmas){
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpHeaders httpHeaders = new HttpHeaders();
        Enumeration<String> enumerations = httpServletRequest.getHeaderNames();
        while (enumerations.hasMoreElements()){
            String key =(String)enumerations.nextElement();
            String value = httpServletRequest.getHeader(key);
            httpHeaders.add(key,value);
        }
        HttpEntity<String> httpEntity = new HttpEntity<String>(parmas == null?null: JSONObject.toJSONString(parmas),httpHeaders);
        ResponseEntity<String> res = restTemplate.exchange(url,method,httpEntity,String.class);
        return res;
    }
}
